<?php
/** 
 * Plugin 'rdt_file' for the 'ameos_formidable' extension.
 *
 * @author	Jerome Schneider <typo3dev@ameos.com>
 */

require_once(PATH_t3lib . "class.t3lib_basicfilefunc.php");

class tx_rdtfile extends formidable_mainrenderlet {

  var $oFileFunc = null; // object for basic file functions
  
  var $sCoolFileName = null;

	function _render() {
		$label = $this->getLabel();
		
		$sFile = $this->_flatten($this->getValue());

		$aHtmlBag = array();
		$sHidden = "";
		$sCompiled = $this->_displayLabel($label);
		$sLink = "";
		$sImage = "";
		$sFilename = "";
		if($sFile != "" && $this->oForm->oDataHandler->_isValid($this->getAbsName())) {

			$aHtmlBag = t3lib_div::array_merge_recursive_overrule($aHtmlBag, $this->_getHumanReadableValue($sFile));
			$sCompiled .= "<div>" . $aHtmlBag["imagetag"] . "</div>";
			
			$aHtmlBag["filelink"] = "<a href=\"" . $aHtmlBag["filepath."]["original"] . "\" target=\"_blank\">" . $sFile . "</a>"; 
			$sCompiled .= " [" . $aHtmlBag["filelink"] . "]<br />";
			$sHidden = "<input type=\"hidden\" name=\"" . $this->_getElementHtmlName() . "[backup]\" id=\"" . $this->_getElementHtmlId() . "[backup]\" value=\"" . $sFile . "\" />";

		} else {
			$aHtmlBag["filelink"] = "";
		}
		
		$sInput = "<input type=\"file\" name=\"" . $this->_getElementHtmlName() . "\" id=\"" . $this->_getElementHtmlId() . "\"" . $this->_getAddInputParams() . " />" . $sHidden;
		$sCompiled .= $sInput;
		
		$aHtmlBag["__compiled"] = $sCompiled;
		$aHtmlBag["input"] = $sInput;

		reset($aHtmlBag);
		return $aHtmlBag;
	}

	function _emptyFormValue($mData) {
		if(is_array($mData) && array_key_exists("error", $mData) && $mData["error"] == 0) {
			// un fichier est upload
			return FALSE;
		} else {
			
			// le fichier n'est pas upload

  			if(is_array($mData) && array_key_exists("backup", $mData) && !empty($mData["backup"])) {
  				return FALSE;
  			} else {
  				if(is_string($mData) && !empty($mData)) {
  					return FALSE;
  				} else {
  					return TRUE;
  				}
  			}
  		}
	}
	
	function _flatten($mData) {

		if(is_array($mData) && array_key_exists("error", $mData) && $mData["error"] == 0) {
			
			// un fichier est upload
			// on intgre la nouvelle donne dans la base
			
			$tmp_name = $mData["tmp_name"];
			
			if(is_null($this->sCoolFileName)){
				$this->sCoolFileName = $this->_MakeCoolFileName($mData["name"]);
			}
			
			$name = $this->sCoolFileName;
			

			$basename = basename($name);
			$target = $this->getFullServerPath($basename);
			$sFile = "";

			if($this->oForm->oDataHandler->_isValid($this->getAbsName())) {
				if(move_uploaded_file($tmp_name, $target)) {
					
					$this->oForm->_debug("moving from <b>[" . $tmp_name . "]</b> to <b>[" . $target . "]</b>", "RDT FILE " . $this->_getName() . " - FILE CORRECTLY UPLOADED AND STORED");
					$sFile = $basename;
				} elseif(file_exists($target)) {
					$sFile = $basename;
				} else {
					$this->oForm->_debug("moving from <b>[" . $tmp_name . "]</b> to <b>[" . $target . "]</b>", "RDT FILE " . $this->_getName() . " - FILE UPLOAD FAILED");
				}
			}
			
			return basename($sFile);

		} else {
			
			// le fichier n'est pas upload
			
			if(is_array($mData) && array_key_exists("backup", $mData) && !empty($mData["backup"])) {
				return $mData["backup"];
			} else {
				if(is_string($mData)) {
					return $mData;
				}
			}
		}

		return "";
	}
	
	function _unFlatten($sData) {
		return $sData;
	}
	
	function _getHumanReadableValue($data) {

		require_once(PATH_t3lib.'class.t3lib_stdgraphic.php');
		require_once(PATH_tslib.'class.tslib_gifbuilder.php');

		$sFilename = $data;

		if(!is_array($sFilename) && !empty($sFilename)) {

			$sUrl = $this->getFullWebPath($sFilename);
			
			if(is_array($mConf = $this->_navConf("/data/imageconf/")) && array_key_exists("userobj", $mConf)) {
				
				// expecting typoscript

				$aParams = array(
					"filename" => $sFilename,
					"abswebpath" => $sUrl,
					"relwebpath" => substr(					// remove "/" before path for typoscript ;(
						$this->getRelWebPath($sFilename),	
						1
					),	//
				);

				$this->oForm->_callUserObj(
					$mConf,
					$aParams,
					FALSE,
					$this
				);

				$aImage = array_pop($this->oForm->aLastTs);

				$bImage = TRUE;

			} else {

				$aImage = $this->conf["image."];
				$aImage["file"] = $this->getRelWebPath($sFilename);

				$bImage = FALSE;

				if(($sWidth = $this->_navConf("/data/width")) !== FALSE) {
					$bImage = TRUE;
					$aImage["file."]["width"] = $sWidth;
				}

				if(($sHeight = $this->_navConf("/data/height")) !== FALSE) {
					$bImage = TRUE;
					$aImage["file."]["height"] = $sHeight;
				}
			}
				
			if($bImage) {

				$sImageTag = $this->oForm->cObj->IMAGE($aImage);
				$sImageFileRel = $this->oForm->cObj->IMG_RESOURCE($aImage);

				if($this->oForm->_defaultTrue("/linktofile", $this->aElement)) {
					$sCompiled = "<a href=\"" . $sUrl . "\" target=\"_blank\">" . $sImageTag . "</a>";
				} else {
					$sCompiled = $sImageTag;
				}

				return array(
					"__compiled" => $sCompiled,
					"imagetag" => $sImageTag,
					"thumb" => $sImageFileRel,
					"filepath" => t3lib_div::getIndpEnv("TYPO3_SITE_URL") . $sImageFileRel,
					"filepath." => array(
						"rel" => $sImageFileRel,
						"original" => $sUrl,
						"original." => array(
							"rel" => $this->getRelWebPath($sFilename),
							"server" => $this->getFullServerPath($sFilename),
						)
					),
					"filename" => basename($sImageFileRel),
					"filename." => array(
						"original" => basename($sFilename),
					)
				);

			} else {
				return array(
					"__compiled" => "<a href=\"" . $sUrl . "\" target=\"_blank\">" . $sFilename . "</a>",
					"filepath." => array(
						"original" => $sUrl,
						"original." => array(
							"rel" => $this->getRelWebPath($sFilename),
							"server" => $this->getFullServerPath($sFilename),
						),
					),
					"filename." => array(
						"original" => basename($sFilename),
					)
				);
			}
		}
		
		return "";
	}

	function getFullServerPath($filename) {

		return	t3lib_div::fixWindowsFilePath(
			t3lib_div::resolveBackPath(
				t3lib_basicFileFunctions::slashPath(PATH_site) . t3lib_basicFileFunctions::slashPath($this->_getTargetDir()) . $filename
			)
        );
	}

	function getFullWebPath($filename) {

		return	$this->oForm->_removeEndingSlash(t3lib_div::getIndpEnv("TYPO3_SITE_URL")) . "/" . $this->oForm->_removeStartingSlash($this->getRelWebPath($filename));
	}
	
	function getRelWebPath($filename) {
		return "/" . t3lib_div::resolveBackPath(
			t3lib_basicFileFunctions::slashPath($this->_getTargetDir()) . $filename
		);
	}
	
	function _getTargetDir() {

		$mTargetDir = $this->_navConf("/data/targetdir/");
		
		if($this->oForm->isRunneable($mTargetDir)) {
			$mTargetDir = $this->callRunneable($mTargetDir);
        }

        return $mTargetDir;
    }
	
	function _MakeCoolFileName($name,$iRand='') {
		
		$name_one = $name;
		
		$basename = basename($name_one);
		$target = $this->getFullServerPath($basename);		
		$rep =  str_replace($basename,"",$target);
		
		$this->oFileFunc = t3lib_div::makeInstance("t3lib_basicFileFunctions");
		$name = $this->oFileFunc->cleanFileName($name);
		$name = strtolower($name);

		$aNomEx = explode(".",$name);
		$sRacine = array_shift($aNomEx);
		$sExt = array_pop($aNomEx);
		
		
		if($iRand == '') {
			$iRand =  1;
		} else {
			$iRand = $iRand + 1;
		}
		
		$sCoolName = $sRacine . "_" . $iRand . "." . $sExt;
		
		if(is_dir($rep)) {
			if($dh = opendir($rep)) {
				
				while(($file = readdir($dh)) !== FALSE) {
					if($sCoolName == $file) {
						$sCoolName = $this->_MakeCoolFileName($name_one,$iRand);
						break;
					}
				}
				
				closedir($dh);
			}
		}

		return $sCoolName;
		exit;
		
	}
}

	if (defined("TYPO3_MODE") && $TYPO3_CONF_VARS[TYPO3_MODE]["XCLASS"]["ext/ameos_formidable/api/base/rdt_file/api/class.tx_rdtfile.php"])	{
		include_once($TYPO3_CONF_VARS[TYPO3_MODE]["XCLASS"]["ext/ameos_formidable/api/base/rdt_file/api/class.tx_rdtfile.php"]);
	}

?>
